import React, { useState, useEffect } from 'react'
import { Shield, Plus, Trash2 } from 'lucide-react'
import { ipWhitelistApi, IpWhitelistEntry } from '@/services/ipWhitelist'
import toast from 'react-hot-toast'

export default function IpWhitelistConfig() {
  const [ipWhitelist, setIpWhitelist] = useState<IpWhitelistEntry[]>([])
  const [newIp, setNewIp] = useState('')
  const [newIpDescription, setNewIpDescription] = useState('')
  const [currentIp, setCurrentIp] = useState('')
  const [loading, setLoading] = useState(true)

  // 加载IP白名单
  useEffect(() => {
    const loadWhitelist = async () => {
      try {
        setLoading(true)
        const whitelistData = await ipWhitelistApi.getWhitelist()
        setIpWhitelist(whitelistData.data)
        setCurrentIp(whitelistData.current_ip)
      } catch (error) {
        console.error('加载IP白名单失败:', error)
        toast.error('加载IP白名单失败')
      } finally {
        setLoading(false)
      }
    }

    loadWhitelist()
  }, [])

  const handleAddIp = async () => {
    if (!newIp.trim()) {
      toast.error('请输入IP地址')
      return
    }

    try {
      await ipWhitelistApi.addIp(newIp.trim(), newIpDescription.trim())
      toast.success('IP已添加到白名单')
      
      // 重新加载白名单
      const whitelistData = await ipWhitelistApi.getWhitelist()
      setIpWhitelist(whitelistData.data)
      
      // 清空输入框
      setNewIp('')
      setNewIpDescription('')
    } catch (error: any) {
      toast.error(error.message || '添加IP失败')
    }
  }

  const handleRemoveIp = async (ip: string) => {
    if (ip === currentIp) {
      toast.error('不能删除自己的IP')
      return
    }

    try {
      await ipWhitelistApi.removeIp(ip)
      toast.success('IP已从白名单移除')
      
      // 重新加载白名单
      const whitelistData = await ipWhitelistApi.getWhitelist()
      setIpWhitelist(whitelistData.data)
    } catch (error: any) {
      toast.error(error.message || '移除IP失败')
    }
  }

  if (loading) {
    return (
      <div className="card">
        <div className="card-content">
          <div className="flex items-center justify-center h-32">
            <div className="text-center">
              <Shield className="w-8 h-8 text-blue-500 mx-auto mb-2 animate-spin" />
              <p className="text-gray-600">加载IP白名单...</p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="card">
      <div className="card-header">
        <h2 className="card-title flex items-center">
          <Shield className="w-5 h-5 mr-2" />
          IP白名单管理
        </h2>
        <p className="card-description">
          管理允许访问设置页面的IP地址
        </p>
      </div>
      <div className="card-content space-y-6">
        {/* 当前IP显示 */}
        <div className="bg-blue-50 border border-blue-200 rounded-md p-4">
          <div className="flex items-center">
            <Shield className="w-5 h-5 text-blue-500 mr-2" />
            <span className="text-sm font-medium text-blue-800">
              当前IP: {currentIp}
            </span>
          </div>
        </div>

        {/* 添加新IP */}
        <div className="space-y-4">
          <h3 className="text-sm font-medium text-gray-700">添加新IP</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="md:col-span-2">
              <input
                type="text"
                value={newIp}
                onChange={(e) => setNewIp(e.target.value)}
                placeholder="IP地址或CIDR网段 (如: 192.168.1.100 或 192.168.1.0/24)"
                className="input"
              />
            </div>
            <div>
              <input
                type="text"
                value={newIpDescription}
                onChange={(e) => setNewIpDescription(e.target.value)}
                placeholder="描述（可选）"
                className="input"
              />
            </div>
          </div>
          <button
            onClick={handleAddIp}
            className="btn-primary"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加IP
          </button>
        </div>

        {/* IP白名单列表 */}
        <div className="space-y-4">
          <h3 className="text-sm font-medium text-gray-700">
            白名单IP列表 ({ipWhitelist.length})
          </h3>
          {ipWhitelist.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              暂无IP白名单
            </div>
          ) : (
            <div className="space-y-2">
              {ipWhitelist.map((entry, index) => (
                <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                  <div className="flex-1">
                    <div className="flex items-center">
                      <span className="font-mono text-sm font-medium">
                        {entry.ip}
                      </span>
                      {entry.ip === currentIp && (
                        <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                          当前IP
                        </span>
                      )}
                    </div>
                    {entry.description && (
                      <p className="text-xs text-gray-600 mt-1">{entry.description}</p>
                    )}
                    <p className="text-xs text-gray-500">
                      添加时间: {new Date(entry.added_at).toLocaleString()}
                    </p>
                  </div>
                  <button
                    onClick={() => handleRemoveIp(entry.ip)}
                    disabled={entry.ip === currentIp}
                    className={`p-2 rounded-md ${
                      entry.ip === currentIp
                        ? 'text-gray-400 cursor-not-allowed'
                        : 'text-red-500 hover:text-red-700 hover:bg-red-50'
                    }`}
                    title={entry.ip === currentIp ? '不能删除当前IP' : '删除此IP'}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 使用说明 */}
        <div className="bg-yellow-50 border border-yellow-200 rounded-md p-4">
          <h4 className="text-sm font-medium text-yellow-800 mb-2">使用说明</h4>
          <ul className="text-xs text-yellow-700 space-y-1">
            <li>• 支持单个IP地址（如：192.168.1.100）</li>
            <li>• 支持CIDR网段（如：192.168.1.0/24）</li>
            <li>• 本地IP（127.0.0.1、localhost）默认允许访问</li>
            <li>• 不能删除当前正在使用的IP</li>
            <li>• 删除IP后该IP将立即失去访问权限</li>
          </ul>
        </div>
      </div>
    </div>
  )
}
